﻿using System.Drawing;
using System.Windows.Forms;
using Pibby.Core;
using Pibby.Core.IO;

namespace Pibby.Controls
{
	public class Mp3ListView : SortableListView
	{
		private IFolder _currentFolder = null;

		public Mp3ListView()
			: base()
		{
			this.MouseDoubleClick += new MouseEventHandler(Mp3ListView_MouseDoubleClick);
		}

		void Mp3ListView_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			if (this.SelectedItems.Count > 0)
			{
				// first item
				ListViewItem item = this.SelectedItems[0];

				if (item.Name == "..")
				{
					var folder = this._currentFolder.Parent;

					if (folder.Exists)
					{
						RefreshContent(folder);
					}
				}
				else   
				{
					var folder = this._currentFolder.Append(item.Text);

					if (folder.Exists)
					{
						RefreshContent(folder);
					}
				}
			}
		}

		public void Configure()
		{
			this.View = View.Details;

			this.Columns.Add("Name", 200, HorizontalAlignment.Left);

			this.FullRowSelect = true;
			this.MultiSelect = true;

			
		}
		
		public void RefreshContent(IFolder folder)
		{
			this._currentFolder = folder;
			this.SmallImageList.ColorDepth = ColorDepth.Depth32Bit;

			var contentLister = new FileListVisitor();

			contentLister.ListContentsOf(folder,
										System.IO.SearchOption.TopDirectoryOnly,
										FileConstants.Mp3FileFilter);


			var subFolders = folder.GetSubfolders();

			if (contentLister.Items.Count > 0 || subFolders.Count > 0)
			{
				this.BeginUpdate();

				this.Items.Clear();
				
				if (this._currentFolder.Path != this._currentFolder.Root)
				{
					var lvItem = new ListViewItem("..", 1);

					lvItem.ImageKey = FileSystemImageListExtensions.FolderKey;
					this.Items.Add(lvItem);
				}

				Icon iconForFile = SystemIcons.WinLogo;

				subFolders.SortByName();

				foreach (var subFolder in subFolders)
				{
					// don't show empty folders...
					if (subFolder.GetFiles().Count > 0)
					{
						this.SmallImageList.AddIconFor(subFolder); 

						var lvItem = new ListViewItem(subFolder.Name);

						lvItem.ImageKey = FileSystemImageListExtensions.FolderKey;
						this.Items.Add(lvItem);
					}
				}
								
				foreach (var item in contentLister.Items)
				{
					this.SmallImageList.AddIconFor(item);

					var lvItem = new ListViewItem(item.Name);

					lvItem.ImageKey = item.Extension;
					this.Items.Add(lvItem);
				}

				this.AutoSizeColumns();
				this.EndUpdate();
			}
		}

		public void ClearContent()
		{
			this.Items.Clear();
		}
	}
}
